package com.jiamao.goplay.ui.discover.vm;

import android.app.Application;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.amap.api.location.AMapLocation;
import com.google.gson.JsonObject;
import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.app.AppApplication;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.HotCityItem;
import com.jiamao.goplay.bean.NearbyItem;
import com.jiamao.goplay.bean.res.ResNearbyList;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.discover.SearchFragment;
import com.tamsiree.rxkit.view.RxToast;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class NeayByVM extends BaseViewModel<DataRepository> {


    private int  page = 1 ;
    public NeayByVM(@NonNull Application application, DataRepository repository) {
        super(application, repository);

        Messenger.getDefault().register(this, Config.MGER_LOCATION_ADDR, AMapLocation.class, new BindingConsumer<AMapLocation>() {
            @Override
            public void call(AMapLocation aMapLocation) {
                Log.d("HTML","NeayByVM BBBBBBBBBBBBBBBBBBBBBB");
                uc.pSwitchEvent.setValue(0);
                getLoadInitData();


            }


        });

        Messenger.getDefault().register(this, Config.MGER_LOCATION_TYPE, Integer.class, new BindingConsumer<Integer>() {
            @Override
            public void call(Integer aMapLocation) {
                Log.d("HTML","AAAAAAAA");
                if (aMapLocation == 1){
                    uc.pSwitchEvent.setValue(4);
                }
            }


        });

//        //模拟10个条目，数据源可以来自网络
//        for (int i = 0; i < 20; i++) {
//
//            NeayByItemVM item = new NeayByItemVM(this);
//                observableList.add(item);
//
//        }

    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<Integer> pSwitchEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> refreshEvent = new SingleLiveEvent<>();

    }


    //条目的点击事件
    public BindingCommand seatchCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(SearchFragment.class.getCanonicalName());
        }
    });


    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableList = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBinding = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();

            itemBinding.set(BR.viewModel, R.layout.discover_nearby_item_layout);

        }
    });


    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableListHot = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBindingHot = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            if (item.getItemType().equals("add")){
                itemBinding.set(BR.viewModel, R.layout.discover_nearby_hot_city_item_add_layout);
            }
            else {
                itemBinding.set(BR.viewModel, R.layout.discover_nearby_hot_city_item_layout);
            }
            //itemBinding.set(BR.viewModel, R.layout.discover_nearby_hot_city_item_layout);

        }
    });

    public void getLoadInitData(){
        //uc.pSwitchEvent.setValue();
        model.getApi().nearbyList(AppApplication.getInstance().lat,AppApplication.getInstance().lot,Config.PAGELIMT,page)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        uc.pSwitchEvent.setValue(1);
                        //      showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResNearbyList>>() {
                    @Override
                    public void onNext(BaseRep<ResNearbyList> baseRep) {
                        super.onNext(baseRep);
                        if (baseRep.isOk()){
                            uc.pSwitchEvent.setValue(0);
                            observableListHot.clear();
                            if (baseRep.getData().getHotCity()==null){
                                return;
                            }
                            for (HotCityItem item: baseRep.getData().getHotCity()){
                                NeayByHotCityItemVM items = new NeayByHotCityItemVM(NeayByVM.this,item);
                                items.multiItemType("city");
                                observableListHot.add(items);
                            }
                            NeayByHotCityItemVM itemsADd = new NeayByHotCityItemVM(NeayByVM.this,null);
                            itemsADd.multiItemType("add");
                            observableListHot.add(itemsADd);
                            observableList.clear();
                            for (NearbyItem item: baseRep.getData().getList()){
                                NeayByItemVM items = new NeayByItemVM(NeayByVM.this,item);
                                observableList.add(items);
                            }

//                                uc.reBtnGetCode.setValue(false);
                            //  reTimeSmsCode();
                        }else {
                            uc.pSwitchEvent.setValue(2);
                            // RxToast.showToastShort(baseRep.getMsg());
//
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //  dismissDialog();
                        uc.pSwitchEvent.postValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }

    public void getLoadData(int i){
        //uc.pSwitchEvent.setValue();
        if (i == 0){
            page = 0;
        }
        page++;
        model.getApi().nearbyList(AppApplication.getInstance().lat,AppApplication.getInstance().lot,Config.PAGELIMT,page)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        uc.refreshEvent.setValue(1);
                        //      showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResNearbyList>>() {
                    @Override
                    public void onNext(BaseRep<ResNearbyList> baseRep) {
                        super.onNext(baseRep);
                        uc.refreshEvent.setValue(0);
                        if (baseRep.isOk()){
                            if (i==0){
                                observableList.clear();

                                observableListHot.clear();
                                if (baseRep.getData().getHotCity()==null){
                                    return;
                                }
                                for (HotCityItem item: baseRep.getData().getHotCity()){
                                    NeayByHotCityItemVM items = new NeayByHotCityItemVM(NeayByVM.this,item);
                                    items.multiItemType("city");
                                    observableListHot.add(items);
                                }
                                NeayByHotCityItemVM itemsADd = new NeayByHotCityItemVM(NeayByVM.this,null);
                                itemsADd.multiItemType("add");
                                observableListHot.add(itemsADd);

                            }



                            if (baseRep.getData().getList()==null){
                                return;
                            }
                            for (NearbyItem item: baseRep.getData().getList()){
                                NeayByItemVM items = new NeayByItemVM(NeayByVM.this,item);
                                observableList.add(items);
                            }

//                                uc.reBtnGetCode.setValue(false);
                            //  reTimeSmsCode();
                        }else {
                            uc.refreshEvent.setValue(2);
                            // RxToast.showToastShort(baseRep.getMsg());
//
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //  dismissDialog();
                        uc.refreshEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });
    }


    public void addLocation(AMapLocation location){
        if (location==null){
            return;
        }
        try {
            //uc.pSwitchEvent.setValue();
            JsonObject jsonObject= new JsonObject();
            jsonObject.addProperty("Latitude",location.getLatitude());
            jsonObject.addProperty("Longitude",location.getLongitude());
            jsonObject.addProperty("Ip","127.0.0.1");
            jsonObject.addProperty("Province",location.getProvince());
            jsonObject.addProperty("City",location.getCity());
            jsonObject.addProperty("Area",location.getDistrict());
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
            KLog.d("html addLocation"+jsonObject.toString());
            model.getApi().addlocations(requestBody)
                    .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                    .compose(RxUtils.schedulersTransformer())  // 线程调度
                    //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                    //    .doOnSubscribe(this) //请求与ViewModel周期同步
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            // uc.refreshEvent.setValue(1);
                            //      showDialog();
                            // dialog.show();
                        }
                    })
                    .subscribe(new BaseSubscriber<BaseRep<ResNearbyList>>() {
                        @Override
                        public void onNext(BaseRep<ResNearbyList> baseRep) {
                            super.onNext(baseRep);
                            //   }
                        }

                        @Override
                        public void onError(Throwable e) {
                            //  dismissDialog();

                        }

                        @Override
                        public void onComplete() {
                            //   dismissDialog();
                        }

                    });
        }catch (Exception e){
            e.printStackTrace();
        }


    }


    public void addCloection(String id,NeayByItemVM vm){
        //uc.pSwitchEvent.setValue();
        model.getApi().detailAddCloection(id)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //   uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep>() {
                    @Override
                    public void onNext(BaseRep baseRep) {
                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            vm.status = 1;
                            vm.addBtnVisibility.set(View.GONE);
                            vm.removeBtnVisibility.set(View.VISIBLE);
                           // status = 1;
                            //uc.updateUICloectionStatus.setValue(1);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }
    public void removeCloection(String id,NeayByItemVM vm){
        //uc.pSwitchEvent.setValue();
        model.getApi().detailRemoveCloection(id)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //  uc.pSwitchEvent.setValue(1);
                        showDialog();
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep>() {
                    @Override
                    public void onNext(BaseRep baseRep) {
                        super.onNext(baseRep);
                        dismissDialog();
                        if (baseRep.isOk()){
                            vm.status = 0;
                            vm.addBtnVisibility.set(View.VISIBLE);
                            vm.removeBtnVisibility.set(View.GONE);
                        //    status = 0;
                          //  uc.updateUICloectionStatus.setValue(0);
                        }else {
                            RxToast.showToastShort(baseRep.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissDialog();
                        //   uc.pSwitchEvent.setValue(2);
                        e.printStackTrace();
                        RxToast.showToastShort("网络出现故障");
                    }

                    @Override
                    public void onComplete() {
                        //   dismissDialog();
                    }

                });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
